package cn.liyicun.cp.cpweb.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import cn.liyicun.cp.cpweb.base.Result;
import cn.liyicun.cp.cpweb.error.LoginAdminRunTimeException;
import cn.liyicun.cp.cpweb.error.LoginRunTimeException;
import cn.liyicun.cp.cpweb.error.WorkRunTimeException;

@ControllerAdvice
public class GlobalExceptionHandler {

	private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ResponseBody
	@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
	public Result<?> invalidParamFormat(MethodArgumentTypeMismatchException e) {
		return new Result<>(406, e.getName() + "参数格式错误");
	}

	@ResponseBody
	@ExceptionHandler(value = MissingServletRequestParameterException.class)
	public Result<?> paramRequired(MissingServletRequestParameterException e) {
		return new Result<>(407, e.getParameterName() + "必填的参数不能为空");
	}

	@ResponseBody
	@ExceptionHandler(value = WorkRunTimeException.class)
	public Result<?> workRunTimeException(WorkRunTimeException e) {
		return Result.create(e.getCode(), e.getMessage());
	}



	@ExceptionHandler(value = LoginRunTimeException.class)
	public void workRunTimeException(LoginRunTimeException e, HttpServletResponse response) {

		try {
			response.sendRedirect("/user/login");
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	}

	@ExceptionHandler(value = LoginAdminRunTimeException.class)
	public void workRunTimeException(LoginAdminRunTimeException e, HttpServletResponse response) {
		try {
			response.sendRedirect("/admin/login");
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	}

	

	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public Result<?> jsonErrorHandler(Exception e) throws Exception {
		logger.error(e.getMessage(), e);
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		return Result.create(500, e.getMessage(), sw.toString());
	}
}